package xin.lhuo.we.server.controller.user;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.lhuo.we.server.vo.ResultVo;
import xin.lhuo.we.server.entity.User;
import xin.lhuo.we.server.enums.ResultEnum;
import xin.lhuo.we.server.exception.WeException;
import xin.lhuo.we.server.form.LoginForm;
import xin.lhuo.we.server.form.UserForm;
import xin.lhuo.we.server.service.IUserService;
import xin.lhuo.we.server.utils.ResultVoUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static xin.lhuo.we.server.constant.HttpConstant.SESSION_USER;

/**
 * @author Lhuo
 * @date 2019/4/30 9:54
 */
@Slf4j
@RestController
@RequestMapping(value = "/user/")
public class UserController {

    private final IUserService userServer;

    public UserController(IUserService userServer) {
        this.userServer = userServer;
    }

    @PostMapping(value = "register")
    public ResultVo register(@Valid UserForm userForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        userServer.saveUser(userForm);
        return ResultVoUtil.success();
    }

    @PostMapping(value = "login")
    public ResultVo login(@Valid LoginForm loginForm, BindingResult bindingResult,
                          HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            throw new WeException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        User user = userServer.login(loginForm.getUsername(), loginForm.getPassword());
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute(SESSION_USER, user);
        return ResultVoUtil.success(user);
    }

    @GetMapping(value = "info")
    public ResultVo userInfo(HttpServletRequest request) {
        //todo 当用户信息发生变化session中信息没有变化
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute(SESSION_USER);
        return ResultVoUtil.success(user);
    }

    @PostMapping(value = "logout")
    public ResultVo logout(HttpServletRequest request) {
        // 从session中删除
        HttpSession httpSession = request.getSession();
        httpSession.removeAttribute(SESSION_USER);

        return ResultVoUtil.success();
    }
}
